from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import TradingPairs
from .serializers import TradingPairsSerializer
from rest_framework.response import Response


# Create your views here.
class TradingPairsViewSet(viewsets.ModelViewSet):
    """
    交易对视图集，提供标准的模型CRUD操作和自定义数据获取接口
    """
    queryset = TradingPairs.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = TradingPairsSerializer

    def get_all_data(self, request, *args, **kwargs):
        """
        获取分页交易对数据（支持过滤查询）
        参数:
            trading_pair: 交易对名称模糊查询
            is_add_data: 是否添加数据过滤
            is_trade: 是否可交易过滤
        返回:
            分页后的JSON数据，包含状态码和数据内容
        """
        # 获取URL查询参数
        search_trading = request.query_params.get('trading_pair')
        search_add_data = request.query_params.get('is_add_data')
        search_trade = request.query_params.get('is_trade')
        
        # 初始化基础数据集
        data = TradingPairs.objects.all()
        
        # 空数据集处理
        if not data:
            return Response({
                "code": 404,
                "data": None,
                "msg": "无数据"
            })

        # 构建动态过滤条件
        if search_trading:
            data = data.filter(trading_pair__icontains=search_trading)  # 交易对名称模糊查询
        if search_add_data:
            data = data.filter(is_add_data=search_add_data)  # 布尔值精确匹配
        if search_trade:
            data = data.filter(is_trade=search_trade)  # 布尔值精确匹配

        # 分页处理流程
        page = self.paginate_queryset(data)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        else:
            return Response({
                "code": 400,
                "data": None,
                "msg": "无分页数据"
            })
